package com.aiti.lulian.utils;

import com.aiti.lulian.components.wx.domain.TokenResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Component
public class WxPublicPlatformTokenUtils {
    private final String WX_TOKEN_REDIS_KEY = "wx:token";
    private final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Value("${wx.token}")
    private String token;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public String getToken(){
        String token = redisTemplate.opsForValue().get(WX_TOKEN_REDIS_KEY);
        if(StringUtils.isEmpty(token)){
            String finalUsl = String.format(GET_TOKEN_URL,appId,appSecret);
            ResponseEntity<TokenResponse> responseEntity = restTemplate.getForEntity(finalUsl, TokenResponse.class);
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                TokenResponse body = responseEntity.getBody();
                token = body.getAccessToken();
                redisTemplate.opsForValue().set(WX_TOKEN_REDIS_KEY,body.getAccessToken(),7200, TimeUnit.SECONDS);
            }else{
                throw new RuntimeException("获取微信Token失败，所有服务号推送功能不可用");
            }
        }
        return token;
    }
}
